﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace NetFrameworkExtensions.Collections
{
  public interface IItemsPage :
    IEnumerable
  {
    int PageNumber { get; }

    int PageCount { get; }

    int PageSize { get; }
  }

  public interface IItemsPage<TItem> :
    IItemsPage,
    IEnumerable<TItem>
  {
  }

  [Serializable]
  public class ItemsPage<TItem> :
    IItemsPage<TItem>
  {
    private TItem[] items;

    public ItemsPage(int pageNumber, int pageSize, int pageCount, IEnumerable<TItem> items)
    {
      if (pageNumber < 0) throw new ArgumentOutOfRangeException("pageNumber");
      if (pageCount < 0) throw new ArgumentOutOfRangeException("pageCount");
      if (pageSize < 1) throw new ArgumentOutOfRangeException("pageSize");
      if (pageNumber >= pageCount) throw new ArgumentOutOfRangeException("pageNumber");
      if (items == null) throw new ArgumentOutOfRangeException("items");

      PageNumber = pageNumber;
      PageCount = pageCount;
      PageSize = pageSize;
      this.items = items.ToArray();
    }

    public int PageNumber { get; private set; }

    public int PageCount { get; private set; }

    public int PageSize { get; private set; }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return items.GetEnumerator();
    }

    public IEnumerator<TItem> GetEnumerator()
    {
      return items.Cast<TItem>().GetEnumerator();
    }
  }
}
